<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import {
  batchDeleteOAuth2ClientsApi,
  deleteOAuth2ClientApi,
  getOAuth2ClientListApi,
  type OAuth2ClientDTO,
} from '#/api/core/oauth2-client';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Popconfirm,
  Row,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';
import { Copy, Edit, Plus, RefreshCw, Search, Trash2 } from 'lucide-vue-next';

import ClientFormModal from './client-form-modal.vue';

// 查询表单
const queryForm = reactive({
  clientId: '',
  clientName: '',
});

// 分页参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 使用 vxe-table
const [Grid, gridApi, gridRef] = useVbenVxeGrid<OAuth2ClientDTO>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      { type: 'checkbox', width: 50, fixed: 'left' },
      { type: 'seq', title: '序号', width: 60, fixed: 'left' },
      {
        field: 'clientId',
        title: '客户端ID',
        minWidth: 150,
        fixed: 'left',
        showOverflow: true,
      },
      {
        field: 'clientName',
        title: '客户端名称',
        minWidth: 150,
        showOverflow: true,
      },
      {
        field: 'authorizationGrantTypes',
        title: '授权类型',
        width: 100,
        showOverflow: true,
        slots: { default: 'grantTypes' },
      },
      {
        field: 'clientAuthenticationMethods',
        title: '认证方法',
        width: 100,
        showOverflow: true,
        slots: { default: 'authMethods' },
      },
      {
        field: 'scopes',
        title: '权限范围',
        width: 100,
        showOverflow: true,
        slots: { default: 'scopes' },
      },
      {
        field: 'redirectUris',
        title: '重定向URI',
        width: 120,
        showOverflow: true,
        slots: { default: 'redirectUris' },
      },
      {
        field: 'createdAt',
        title: '创建时间',
        width: 160,
        showOverflow: true,
        slots: { default: 'createdAt' },
      },
      {
        title: '操作',
        width: 200,
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 模态框状态
const modalVisible = ref(false);
const currentClient = ref<OAuth2ClientDTO | null>(null);

// 解析JSON字符串字段为数组
function parseClientData(client: any): OAuth2ClientDTO {
  const parseJsonField = (field: any): any[] => {
    if (!field) return [];
    if (Array.isArray(field)) return field;
    if (typeof field === 'string') {
      try {
        const parsed = JSON.parse(field);
        return Array.isArray(parsed) ? parsed : [];
      } catch (e) {
        console.warn('解析JSON字段失败:', field, e);
        return [];
      }
    }
    return [];
  };

  return {
    ...client,
    clientAuthenticationMethods: parseJsonField(client.clientAuthenticationMethods),
    authorizationGrantTypes: parseJsonField(client.authorizationGrantTypes),
    redirectUris: parseJsonField(client.redirectUris),
    scopes: parseJsonField(client.scopes),
  };
}

// 加载数据
async function loadData() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const params = {
      page: queryParams.pageNum,
      size: queryParams.pageSize,
      clientId: queryForm.clientId || undefined,
      clientName: queryForm.clientName || undefined,
    };

    const response = await getOAuth2ClientListApi(params);

    // 解析JSON字符串字段
    const parsedData = (response.list || []).map(parseClientData);

    gridApi.setState({
      gridOptions: {
        data: parsedData,
        loading: false,
        pagerConfig: {
          total: response.total,
          currentPage: queryParams.pageNum,
          pageSize: queryParams.pageSize,
        },
      },
    });
  } catch (error) {
    console.error('加载客户端列表失败:', error);
    message.error('加载客户端列表失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1;
  loadData();
}

// 重置
function handleReset() {
  queryForm.clientId = '';
  queryForm.clientName = '';
  queryParams.pageNum = 1;
  loadData();
}

// 新增
function handleAdd() {
  currentClient.value = null;
  modalVisible.value = true;
}

// 编辑
function handleEdit(row: OAuth2ClientDTO) {
  currentClient.value = row;
  modalVisible.value = true;
}

// 删除
async function handleDelete(row: OAuth2ClientDTO) {
  try {
    await deleteOAuth2ClientApi(row.id);
    message.success('删除成功');
    loadData();
  } catch (error) {
    console.error('删除客户端失败:', error);
    message.error('删除客户端失败');
  }
}

// 批量删除
async function handleBatchDelete() {
  const selectRecords = gridRef.value?.getCheckboxRecords() || [];
  if (selectRecords.length === 0) {
    message.warning('请选择要删除的客户端');
    return;
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectRecords.length} 个客户端吗？`,
    onOk: async () => {
      try {
        const ids = selectRecords.map((record) => record.id);
        await batchDeleteOAuth2ClientsApi(ids);
        message.success('批量删除成功');
        loadData();
      } catch (error) {
        console.error('批量删除客户端失败:', error);
        message.error('批量删除客户端失败');
      }
    },
  });
}

// 复制到剪贴板
function copyToClipboard(text: string) {
  navigator.clipboard.writeText(text).then(() => {
    message.success('已复制到剪贴板');
  });
}

// 格式化时间
function formatDateTime(dateStr?: string) {
  if (!dateStr) return '-';
  return new Date(dateStr).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

// 截断文本
function truncateText(text: string, maxLength: number = 15) {
  if (!text) return '';
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
}

// 分页改变
function handlePageChange({ currentPage, pageSize }: any) {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  loadData();
}

// 模态框成功回调
function handleModalSuccess() {
  loadData();
}

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="flex h-full flex-col p-4">
    <!-- 查询表单 -->
    <Card :bordered="false" class="mb-4 flex-shrink-0">
      <Form layout="inline">
        <FormItem label="客户端ID">
          <Input
            v-model:value="queryForm.clientId"
            placeholder="请输入客户端ID"
            style="width: 200px"
            allow-clear
            @press-enter="handleQuery"
          />
        </FormItem>
        <FormItem label="客户端名称">
          <Input
            v-model:value="queryForm.clientName"
            placeholder="请输入客户端名称"
            style="width: 200px"
            allow-clear
            @press-enter="handleQuery"
          />
        </FormItem>
        <FormItem>
          <Space>
            <Button type="primary" @click="handleQuery">
              <template #icon>
                <Search :size="16" />
              </template>
              查询
            </Button>
            <Button @click="handleReset">
              <template #icon>
                <RefreshCw :size="16" />
              </template>
              重置
            </Button>
          </Space>
        </FormItem>
      </Form>
    </Card>

    <!-- 表格 -->
    <Card :bordered="false" class="flex flex-1 flex-col overflow-hidden">
      <div class="mb-4 flex flex-shrink-0 justify-between">
        <Space>
          <Button type="primary" @click="handleAdd">
            <template #icon>
              <Plus :size="16" />
            </template>
            新增客户端
          </Button>
          <Button danger @click="handleBatchDelete">
            <template #icon>
              <Trash2 :size="16" />
            </template>
            批量删除
          </Button>
        </Space>
      </div>

      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
        <!-- 授权类型 -->
        <template #grantTypes="{ row }">
          <div v-if="row.authorizationGrantTypes && row.authorizationGrantTypes.length > 0">
            <Tooltip>
              <template #title>
                <div v-for="(type, index) in row.authorizationGrantTypes" :key="index">
                  {{ type }}
                </div>
              </template>
              <Tag color="blue">
                {{ row.authorizationGrantTypes.length }} 个类型
              </Tag>
            </Tooltip>
          </div>
          <span v-else class="text-gray-400">-</span>
        </template>

        <!-- 认证方法 -->
        <template #authMethods="{ row }">
          <div v-if="row.clientAuthenticationMethods && row.clientAuthenticationMethods.length > 0">
            <Tooltip>
              <template #title>
                <div v-for="(method, index) in row.clientAuthenticationMethods" :key="index">
                  {{ method }}
                </div>
              </template>
              <Tag color="green">
                {{ row.clientAuthenticationMethods.length }} 个方法
              </Tag>
            </Tooltip>
          </div>
          <span v-else class="text-gray-400">-</span>
        </template>

        <!-- 权限范围 -->
        <template #scopes="{ row }">
          <div v-if="row.scopes && row.scopes.length > 0">
            <Tooltip>
              <template #title>
                <div v-for="(scope, index) in row.scopes" :key="index">
                  {{ scope }}
                </div>
              </template>
              <Tag color="purple">
                {{ row.scopes.length }} 个权限
              </Tag>
            </Tooltip>
          </div>
          <span v-else class="text-gray-400">-</span>
        </template>

        <!-- 重定向URI -->
        <template #redirectUris="{ row }">
          <div v-if="row.redirectUris && row.redirectUris.length > 0">
            <Tooltip>
              <template #title>
                <div v-for="(uri, index) in row.redirectUris" :key="index">
                  {{ uri }}
                </div>
              </template>
              <Tag color="orange">
                {{ row.redirectUris.length }} 个URI
              </Tag>
            </Tooltip>
          </div>
          <span v-else class="text-gray-400">-</span>
        </template>

        <!-- 创建时间 -->
        <template #createdAt="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>

        <!-- 操作 -->
        <template #action="{ row }">
          <Space>
            <Button type="link" size="small" @click="handleEdit(row)">
              <template #icon>
                <Edit :size="14" />
              </template>
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              @click="copyToClipboard(row.clientId)"
            >
              <template #icon>
                <Copy :size="14" />
              </template>
              复制ID
            </Button>
            <Popconfirm
              title="确定要删除这个客户端吗？"
              @confirm="handleDelete(row)"
            >
              <Button type="link" danger size="small">
                <template #icon>
                  <Trash2 :size="14" />
                </template>
                删除
              </Button>
            </Popconfirm>
          </Space>
        </template>
        </Grid>
      </div>
    </Card>

    <!-- 表单模态框 -->
    <ClientFormModal
      v-model:visible="modalVisible"
      :client-data="currentClient"
      @success="handleModalSuccess"
    />
  </div>
</template>

<style scoped>
.text-gray-400 {
  color: #9ca3af;
}
</style>

